<template>
  <div>
    <div class="installPrepare" v-if="installPrepareStep">
      <div>
        <p>1、请核对盒子外壳粘贴SN与二维码贴纸SN一致，如不一致请联系管理员。</p>
        <p>2、如有多个房间请提醒店长各房间的WiFi名称和密码不能一致，以免影响使用效果。</p>
        <p>3、请在二维码贴纸上填写该房间的WiFi名称和密码。</p>
      </div>
      <div style="text-align: center;">
        <span>请确保完成以上操作后再点击"下一步"</span>
      </div>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="primary" @click="toInstallSnCheck" style="width: 100%;">下一步</el-button>
      </div>
    </div>
    <div class="installSnCheck" style="padding: 10px 16px;" v-if="installSnCheckStep">
      <div>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="SN编码" prop="deviceName" v-if="allowReinputSn">
            <el-input v-model="form.deviceName" placeholder="请输入SN编码">
              <el-button slot="append" type="primary" @click="scan">扫码录入</el-button>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center;">
        <span>盒子上贴有唯一的SN编码</span>
      </div>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="info" @click="backToPrepare" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallHotelInfo" style="width: 45%;">下一步</el-button>
      </div>
    </div>
    <div class="installHotelInfo" style="padding: 10px 16px;" v-if="installHotelInfoStep">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="SN编码" prop="deviceName">
          <span style="line-height: 40px; color: #606266;">{{ form.deviceName }}</span>
        </el-form-item>
        <el-form-item label="所属公寓" prop="hotelId">
          <el-select
            v-model="form.hotelId"
            placeholder="请选择公寓"
            clearable
            style="width: 100%">
            <el-option
              v-for="item in hotelOptions"
              :key="item.hotelId"
              :label="item.hotelName"
              :value="item.hotelId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="房间地址" prop="roomAddress">
          <el-input v-model="form.roomAddress" placeholder="请输入房间地址" />
        </el-form-item>
        <el-form-item label="房间户型" prop="roomLayout">
          <el-select
            v-model="form.roomLayout"
            placeholder="请输入房间户型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.device_hotel_layout"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="控电功率（千瓦）" prop="roomPowerCapacity" style="width: 100%">
          <el-input v-model="form.roomPowerCapacity" placeholder="请输入控电功率" />
        </el-form-item>
        <el-form-item label="用电单价（元）" prop="roomPowerPrice" style="width: 100%">
          <el-input v-model="form.roomPowerPrice" placeholder="请输入用电单价" />
        </el-form-item>
      </el-form>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="info" @click="backToSnCheck" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallPrepareWifi" style="width: 45%;">下一步</el-button>
      </div>
    </div>
    <div class="installPrepare" v-if="installPrepareWifiStep">
      <div>
        <p>1、请设置手机热点为默认Wi-Fi，并保持打开等待设置完成后关闭。<br>
          WiFi名称：abc<br>
          WiFi密码：abc12345
        </p>
        <p>2、请连接盒子的供电线，等待绿灯亮起后长按K1。</p>
        <p>3、请观察红灯先闪烁3次，再闪烁3次后亮起，等待5秒绿灯亮起后松开K1，如连接异常请重试以上操作。</p>
      </div>
      <div style="text-align: center;">
        <span>请确保完成以上操作后再点击"下一步"</span>
      </div>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="info" @click="backToHotelInfo" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallWifi" style="width: 45%;">下一步</el-button>
      </div>
    </div>
    <div class="installWifi" style="padding: 10px 16px;" v-if="installWifiStep">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="Wi-Fi名称" prop="wifiName" v-if="form.deviceId">
          <el-input v-model="form.wifiName" placeholder="请输入Wi-Fi名称" />
        </el-form-item>
        <el-form-item label="Wi-Fi密码" prop="wifiPswd" v-if="form.deviceId">
          <el-input v-model="form.wifiPswd" placeholder="请输入Wi-Fi密码" />
        </el-form-item>
      </el-form>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="info" @click="backToPrepareWifi" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallCttime" style="width: 45%;">下一步</el-button>
      </div>
    </div>
    <div class="installCttime" style="padding: 10px 16px;" v-if="installCttimeStep">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="长通时段(开始时间)" prop="ctBeginTime" style="width: 100%">
<!--          <el-input v-model="form.ctBeginTime" placeholder="请输入开始时间(HH:mm)" />-->
          <el-time-picker
            v-model="form.ctBeginTime"
            style="width: 100%"
            format='HH:mm'
            value-format="HH:mm"
            :editable="false">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="长通时段(结束时间)" prop="ctEndTime" style="width: 100%">
<!--          <el-input v-model="form.ctEndTime" placeholder="请输入结束时间(HH:mm)" />-->
          <el-time-picker
            v-model="form.ctEndTime"
            style="width: 100%"
            format='HH:mm'
            value-format="HH:mm"
            :editable="false">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="info" @click="backToWifi" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallFixDevice" style="width: 45%;">下一步</el-button>
      </div>
    </div>
    <div class="installFixDevice" style="padding: 10px 16px;" v-if="installFixDeviceStep">
      <div>
        <p>请在上报设备列表MAC中选择固定设备<br><span style="float: right;color: #07c160;" @click="handleReportDevice">刷新上报</span></p><br>
      </div>
      <div v-if="fixDeviceList.length > 0">
        <el-table ref="reportDeviceTable" v-loading="reportDeviceLoading" :data="fixDeviceList" @selection-change="handleSelectDevice">
          <el-table-column label="设为固定" align="center" prop="flag" type="selection" width="55" />
          <el-table-column label="设备MAC" align="center" prop="mac" />
        </el-table>
      </div>
      <div>
        <span>点击“刷新上报”查看设备MAC列表，已勾选的设备MAC为之前设置的固定设备。设置固定设备与盒子后期能否正常使用有直接关系，请务必在上报的设备MAC列表中与房主确定所有的固定设备，后续房间增加固定设备需联系安装人员进行设置</span>
      </div>
      <div style="text-align: center;margin: 1.2em 0 auto;padding: 1em 2em 0 2em;">
        <el-button type="info" @click="backToCttime" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallSaveFixDevice" style="width: 45%;">确 定</el-button>
      </div>
      <div style="text-align: center;margin: 1.2em auto;padding: 0 2em;">
        <el-button type="primary" @click="toInstallTest" style="width: 100%;">下一步</el-button>
      </div>
    </div>
    <div class="installTest" style="padding: 10px 16px;" v-if="installTestStep">
      <div>
        <p>房间名称：{{form.roomName}}</p>
        <p>SN编码：{{form.deviceName}}</p>
        <p><span style="color: #07c160;" @click="handleCircuitSwitchChange('11')">下发通电指令</span><span style="margin-left: 50px; color: #07c160;" @click="handleCircuitSwitchChange('01')">下发断电指令</span></p>
      </div>
      <div>
        <span>请核实下发指令后，盒子执行状态是否正常。</span>
      </div>
      <div style="text-align: center;margin: 1.2em auto;padding: 1em 2em;">
        <el-button type="info" @click="backToFixDevice" style="width: 45%; margin-right: 4%;">上一步</el-button>
        <el-button type="primary" @click="toInstallFinish" style="width: 45%;">测试完成</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import wx from 'weixin-js-sdk'

import {
  getWxSign,
  getDeviceBySn,
  updateDevice,
  updateDeviceWifi,
  updateDeviceCttime,
  checkDeviceStatus,
  saveFixDevice,
  reportFixDevice, listFixDevice, changeDeviceCircuitSwitch
} from "@/api/device/device";
import {parseStrEmpty} from "@/utils/ruoyi";

export default {
  name: "DeviceInstall",
  dicts: ['device_hotel_layout'],
  data() {
    return {
      installPrepareStep: true,
      installSnCheckStep: false,
      installHotelInfoStep: false,
      installPrepareWifiStep: false,
      installWifiStep: false,
      installCttimeStep: false,
      installFixDeviceStep: false,
      installTestStep: false,
      // 表单参数
      form: {
        roomName: '',
        deviceName: '',
        ctBeginTime: '22:00',
        ctEndTime: '08:00'
      },
      // 店长选项
      hotelOptions: [],
      // 上报设备弹出层遮罩层
      reportDeviceLoading: true,
      // 固定设备表格数据
      fixDeviceList: [],
      // 选中设备MAC
      macs: [],
      timer: null,
      // 是否允许重新输入SN编码
      allowReinputSn: true,
      // 保存原始的SN编码用于比较
      originalDeviceName: ''
    }
  },
  created () {
    this.getSign();
  },
  methods: {
    /**
     * 获取微信签名信息
     */
    getSign() {
      //解决ios第一次无法调用微信扫一扫的功能，如果直接使用location.href.split('#')[0]进行获取链接的话，在IOS系统中第一次可能会无法进行正常的签名操作。
      //原因：微信会对IOS页面链接做处理，虽然使用location.href.split('#')[0]获取输出的链接，为当前的页面，但是实际上，在IOS页面的链接，并不是这一个链接，所以会导致签名失败的情况
      let purl = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.localStorage.getItem('scanUrl');
      let dataForm = {
        'url': purl
      }
      //请求后端，获取微信签名信息
      getWxSign(dataForm).then((res) => {
        if (res.code == 200) {
          let configData = {
            debug: false,
            appId: res.appId, // 必填，公众号的唯一标识
            timestamp: "" + res.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.nonceStr, // 必填，生成签名的随机串
            signature: res.signature,// 必填，签名
            jsApiList: ['scanQRCode', 'checkJsApi']
          }
          wx.config(configData);
        } else {
          alert("获取签名信息失败，请刷新页面重新获取");
        }
      });
    },
    /**
     * 调用微信扫一扫功能
     */
    scan() {
      let _that = this;
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: ['scanQRCode'],
          success: function (res) {
            if (res.checkResult.scanQRCode === true) {
              wx.scanQRCode({ // 微信扫一扫接口
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                  let result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
                  if (result.indexOf(",")>0) {
                    _that.form.deviceName = result.substr(result.indexOf(",")+1);
                  } else {
                    _that.form.deviceName = result;
                  }
                }
              })
            } else {
              alert("抱歉，当前客户端版本不支持扫一扫");
            }
          },
          fail: function (res) { // 检测getNetworkType该功能失败时处理
            alert('fail' + res)
          }
        });
      });
      //错误信息
      wx.error(function (res) {
        alert("出错了：" + res.errMsg);
      });
    },

    // 上报固定设备
    handleReportDevice() {
      let _that = this;
      _that.$modal.loading("正在上报固定设备信息，请稍后...")
      reportFixDevice({ "deviceName": _that.form.deviceName }).then(response => {
        if (response.code == 200) {
          _that.deviceName = _that.form.deviceName;
          _that.reportDeviceLoading = true;
          _that.fixDeviceList = [];

          _that.timer = setInterval(function () {
            listFixDevice({ "deviceName": _that.form.deviceName }).then(res => {
              console.log("res: "+JSON.stringify(res))
              _that.$modal.closeLoading();
              clearInterval(_that.timer);
              if (res.total > 0) {
                _that.reportDeviceLoading = false;
                _that.fixDeviceList = res.rows;

                _that.$nextTick(()=>{
                  _that.fixDeviceList.forEach(device => {
                    if(device.flag == "1"){
                      console.log("设备mac："+device.mac+"为固定设备")
                      console.log(_that.$refs.reportDeviceTable);
                      _that.$refs.reportDeviceTable.toggleRowSelection(device,true);
                    }
                  })
                })
              }
            });
          }, 1500)
        }
      });
    },

    // 多选框选中固定设备
    handleSelectDevice(selection) {
      this.macs = selection.map(item => item.mac)
    },

    // 电路开关修改
    handleCircuitSwitchChange(circuitSwitch) {
      let _that = this;
      let text = circuitSwitch === "01" ? "断电" : "通电";

      changeDeviceCircuitSwitch(_that.form.productId, _that.form.deviceId, _that.form.deviceName, circuitSwitch).then(response => {
        this.$modal.msgSuccess(text + "指令下发成功");
      });
    },

    checkInstallWifiStep() {

    },
    toInstallSnCheck() {
      // 仅显示SN校验步骤
      this.installPrepareStep = false;
      this.installSnCheckStep = true;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = false;
      this.installWifiStep = false;
      this.installCttimeStep = false;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    toInstallHotelInfo() {
      let _that = this;
      if (!_that.form.deviceName) {
        _that.$modal.msgWarning("请输入SN编码");
      } else {
        // 如果已经有设备信息且SN编码没有变化，直接进入下一步
        if (_that.form.deviceId && _that.form.deviceName === _that.originalDeviceName) {
          // 禁用重新输入SN编码
          _that.allowReinputSn = false;
          
          // 仅显示公寓信息步骤
          _that.installPrepareStep = false;
          _that.installSnCheckStep = false;
          _that.installHotelInfoStep = true;
          _that.installPrepareWifiStep = false;
          _that.installWifiStep = false;
          _that.installCttimeStep = false;
          _that.installFixDeviceStep = false;
          _that.installTestStep = false;
        } else {
          // 重新获取设备信息
          getDeviceBySn({ "deviceName": this.form.deviceName }).then(response => {
            if (response.code == 200 && response.data != null) {
              _that.form = response.data;
              _that.hotelOptions = response.hotels;
              // 保存原始SN编码
              _that.originalDeviceName = _that.form.deviceName;
              // 禁用重新输入SN编码
              _that.allowReinputSn = false;

              // 仅显示公寓信息步骤
              _that.installPrepareStep = false;
              _that.installSnCheckStep = false;
              _that.installHotelInfoStep = true;
              _that.installPrepareWifiStep = false;
              _that.installWifiStep = false;
              _that.installCttimeStep = false;
              _that.installFixDeviceStep = false;
              _that.installTestStep = false;
            } else {
              _that.$modal.msgError("设备不存在，请重新输入SN编码");
            }
          });
        }
      }
    },
    toInstallPrepareWifi() {
      let _that = this;
      if (_that.form.deviceId != null) {
        updateDevice(_that.form).then(response => {
          if (response.code == 200) {
            _that.$modal.msgSuccess("设置设备信息成功");
            // 仅显示WiFi准备步骤
            _that.installPrepareStep = false;
            _that.installSnCheckStep = false;
            _that.installHotelInfoStep = false;
            _that.installPrepareWifiStep = true;
            _that.installWifiStep = false;
            _that.installCttimeStep = false;
            _that.installFixDeviceStep = false;
            _that.installTestStep = false;
          } else {
            _that.$modal.msgError("设置设备信息失败，请重新设置");
          }
        });
      }
    },
    toInstallWifi() {
      let _that = this;

      _that.$modal.loading("正在查询盒子状态，请稍后...")
      // 查询盒子连接物联网状态
      checkDeviceStatus({ "deviceName": _that.form.deviceName }).then(response => {
        _that.$modal.closeLoading();

        if (response.code === 200) {
          if (response.status === 0) {
            _that.$modal.msgError("盒子连接失败，设备离线");
          } else if (response.status === 1) {
            _that.$modal.msgSuccess("盒子连接成功");

            // 仅显示WiFi设置步骤
            _that.installPrepareStep = false;
            _that.installSnCheckStep = false;
            _that.installHotelInfoStep = false;
            _that.installPrepareWifiStep = false;
            _that.installWifiStep = true;
            _that.installCttimeStep = false;
            _that.installFixDeviceStep = false;
            _that.installTestStep = false;
          } else if (response.status === 2) {
            _that.$modal.msgError("盒子连接失败，设备获取失败");
          } else if (response.status === 3) {
            _that.$modal.msgError("盒子连接失败，设备未激活");
          } else {
            _that.$modal.msgError("盒子连接失败，设备状态未知");
          }
        } else {
          _that.$modal.msgError("盒子连接失败，请重试");
        }
      });
    },
    toInstallCttime() {
      let _that = this;
      if (parseStrEmpty(_that.form.deviceId) !== "" && parseStrEmpty(_that.form.wifiName) !== "" && parseStrEmpty(_that.form.wifiPswd) !== "") {
        _that.$modal.confirm('为保证电力盒子正常工作，请修改房间wifi为设置的' + _that.form.wifiName + '/' + _that.form.wifiPswd).then(function() {
          _that.$modal.loading("正在设置盒子wifi信息，请稍后...")
          // 设置盒子wifi信息
          updateDeviceWifi(_that.form).then(response => {
            _that.$modal.closeLoading();

            if (response.code == 200) {
              _that.$modal.msgSuccess("设置设备房间WiFi成功");

              // 仅显示长通时段步骤
              _that.installPrepareStep = false;
              _that.installSnCheckStep = false;
              _that.installHotelInfoStep = false;
              _that.installPrepareWifiStep = false;
              _that.installWifiStep = false;
              _that.installCttimeStep = true;
              _that.installFixDeviceStep = false;
              _that.installTestStep = false;
            } else {
              _that.$modal.msgError("设置设备房间WiFi失败，请重新设置");
            }
          });
        }).catch(() => {});
      } else {
        _that.$modal.msgWarning("请输入Wi-Fi名称/密码");
      }
    },
    toInstallFixDevice() {
      let _that = this;
      if (parseStrEmpty(_that.form.deviceId) !== "" && parseStrEmpty(_that.form.ctBeginTime) !== "" && parseStrEmpty(_that.form.ctEndTime) !== "") {
        // 设置盒子wifi信息
        // updateDeviceCttime(_that.form).then(response => {
        //   if (response.code == 200) {
            _that.$modal.msgSuccess("设置设备长通时段成功");

            // 仅显示固定设备步骤
            _that.installPrepareStep = false;
            _that.installSnCheckStep = false;
            _that.installHotelInfoStep = false;
            _that.installPrepareWifiStep = false;
            _that.installWifiStep = false;
            _that.installCttimeStep = false;
            _that.installFixDeviceStep = true;
            _that.installTestStep = false;
          // } else {
          //   _that.$modal.msgError("设置设备长通时段失败，请重新设置");
          // }
        // });
      } else {
        _that.$modal.msgWarning("请输入长通时段的开始和结束时间");
      }
    },
    toInstallSaveFixDevice() {
      let _that = this;
      _that.$modal.confirm('是否确认将所选设备设置为固定设备？').then(function() {
        console.log("deviceName="+_that.form.deviceName+", macs="+_that.macs)
        return saveFixDevice(_that.form.deviceName, _that.macs);
      }).then(() => {
        _that.$modal.msgSuccess("设置固定设备成功");
      }).catch(() => {});
    },
    toInstallTest() {
      let _that = this;
      // 仅显示测试步骤
      _that.installPrepareStep = false;
      _that.installSnCheckStep = false;
      _that.installHotelInfoStep = false;
      _that.installPrepareWifiStep = false;
      _that.installWifiStep = false;
      _that.installCttimeStep = false;
      _that.installFixDeviceStep = false;
      _that.installTestStep = true;
    },
    toInstallFinish() {
      location.reload()
    },
    
    // 上一步按钮方法（仅展示目标上一步）
    backToPrepare() {
      this.installPrepareStep = true;
      this.installSnCheckStep = false;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = false;
      this.installWifiStep = false;
      this.installCttimeStep = false;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    backToSnCheck() {
      // 允许重新输入SN编码
      this.allowReinputSn = true;
      this.installPrepareStep = false;
      this.installSnCheckStep = true;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = false;
      this.installWifiStep = false;
      this.installCttimeStep = false;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    backToHotelInfo() {
      this.installPrepareStep = false;
      this.installSnCheckStep = false;
      this.installHotelInfoStep = true;
      this.installPrepareWifiStep = false;
      this.installWifiStep = false;
      this.installCttimeStep = false;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    backToPrepareWifi() {
      this.installPrepareStep = false;
      this.installSnCheckStep = false;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = true;
      this.installWifiStep = false;
      this.installCttimeStep = false;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    backToWifi() {
      this.installPrepareStep = false;
      this.installSnCheckStep = false;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = false;
      this.installWifiStep = true;
      this.installCttimeStep = false;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    backToCttime() {
      this.installPrepareStep = false;
      this.installSnCheckStep = false;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = false;
      this.installWifiStep = false;
      this.installCttimeStep = true;
      this.installFixDeviceStep = false;
      this.installTestStep = false;
    },
    backToFixDevice() {
      this.installPrepareStep = false;
      this.installSnCheckStep = false;
      this.installHotelInfoStep = false;
      this.installPrepareWifiStep = false;
      this.installWifiStep = false;
      this.installCttimeStep = false;
      this.installFixDeviceStep = true;
      this.installTestStep = false;
    }
  }
};
</script>

<style scoped lang="scss">
.installPrepare>div:first-child>p {
  padding: 1em;
}

.installPrepare>div:first-child+div>span {
  margin-left: 0.5em;
  position: relative;
  top: -0.3em;
  color: rgba(16,16,16,.67);
}

.installPrepareWiFi>div:first-child>p {
  padding: 1em;
}

.installPrepareWiFi>div:first-child+div>span {
  margin-left: 0.5em;
  position: relative;
  top: -0.3em;
  color: rgba(16,16,16,.67);
}
</style>
